﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIScrollMono : MonoBehaviour {

    public static UIScrollMono intance;

    private RectTransform _selfTrans;

    public RectTransform l, m, r;
    private RectTransform lref, mref, rref; //用来区分三个面块的区域的引用

    public float _childItemWidth = -1558.5f;

    public Vector3 vl, vm, vr;

    private Canvas canvas;

    private Vector3 offsetX;

    [HideInInspector] public Vector3 anchorLeft, anchorRight;

    public enum ViewMoveDir { none, left, right }

    public ViewMoveDir currentMoveDir = ViewMoveDir.none;

    private void Start()
    {
        Init();
    }

    public void Init()
    {
        intance = this;

        vl = l.position;
        vm = m.position;
        vr = r.position;

        offsetX = vm - vl;

        anchorLeft = vm - 2 * offsetX;
        anchorRight = vm + 2 * offsetX;
        Debug.LogFormat("vm: {0}  vl: {1}  anchorleft:{2}", vm, vl, anchorLeft);

        _selfTrans = GetComponent<RectTransform>();

        canvas = WindowManager.Instance.canvas;
    }

    void Update()
    {

        if (Input.GetMouseButtonUp(0))
        {
            OnItemDragUp();
        }
    }

    public void ResetParent()
    {
        _selfTrans.DetachChildren();
        _selfTrans.anchoredPosition = Vector2.zero;
        l.SetParent(_selfTrans);
        m.SetParent(_selfTrans);
        r.SetParent(_selfTrans);

        currentMoveDir = ViewMoveDir.none;
    }

    public void OnItemDragUp()
    {
        //DOTween.Kill(this);
        if (_selfTrans.anchoredPosition.x <= _childItemWidth / 2 * -1)
        {

            _selfTrans.DOMoveX(vl.x, 0.5f).OnComplete(() => {

                currentMoveDir = ViewMoveDir.left;

                RectTransform s = null;
                if (l.position.x < (vm - offsetX * 1.5f).x) s = l;
                if (m.position.x < (vm - offsetX * 1.5f).x) s = m;
                if (r.position.x < (vm - offsetX * 1.5f).x) s = r;

                s.position = vr;
                ResetParent();

            });
        }
        else if (_selfTrans.anchoredPosition.x > _childItemWidth / 2)
        {
            _selfTrans.DOMoveX(vr.x, 0.5f).OnComplete(() => {
                currentMoveDir = ViewMoveDir.right;

                RectTransform s = null;
                if (l.position.x > (vm + offsetX).x + _childItemWidth / 2) s = l;
                if (m.position.x > (vm + offsetX).x + _childItemWidth / 2) s = m;
                if (r.position.x > (vm + offsetX).x + _childItemWidth / 2) s = r;

                s.position = vl;
                ResetParent();
            });
        }
        else
        {
            currentMoveDir = ViewMoveDir.none;

            _selfTrans.DOMoveX(vm.x, 0.5f);
        }
    }
}
